<template>
  <el-form
    style="width: 700px"
    :model="form"
    ref="form1"
    label-width="120px"
    class="demo-ruleForm"
    :rules="rules"
  >
    <el-form-item label="菜品名称" prop="dishName">
      <el-input v-model="form.dishName"></el-input>
    </el-form-item>
    <el-form-item label="菜品图片" prop="dishPic">
      <el-upload
        class="avatar-uploader"
        name="avatar"
        action="http://localhost:9000/upload"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
      >
        <img v-if="form.dishPic" :src="form.dishPic" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item label="菜品价格" prop="price">
      <el-input v-model="form.price"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="danger" v-on:click="add(form1)" round>新增</el-button>
      <el-button type="warning" @click="resetForm(form1)" round>取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, FormInstance, FormRules } from "element-plus";

import $http from "@/http";
const form1 = ref<FormInstance>();
const form: any = reactive<any>({
  dishName: "",
  dishPic: "",
  price: "",
});

const rules = reactive({
  dishName: [{ required: true, message: "菜品名不能为空", trigger: "blur" }],
  dishPic: [{ required: true, message: "菜品图片不能为空", trigger: "blur" }],
  price: [{ required: true, message: "菜品价格不能为空", trigger: "blur" }],
});

const router = useRouter();
// 新增菜品
const add = (f: FormInstance | undefined) => {
  if (!f) return;
  f.validate((valid, field) => {
    if (valid) {
      $http.dishApi
        .add(form)
        .then((res) => {
          //console.log(res);
          if (res.data.code == 200) {
            ElMessage.success("菜品增加成功");
            router.push("/home/dish-list");
          }
        })
        .catch((err) => console.log(err));
    } else {
      ElMessage.error("表单填写错误");
    }
  });
};

// 重置表单
const resetForm = (f: FormInstance | undefined) => {
  if (!f) return;
  f.resetFields();
};

//
const handleAvatarSuccess = (res: any, file: any) => {
  //console.log(res)
  form.dishPic = "http://localhost:9000/" + res.filename;
};
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>